package com.bwie.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bwie.mapper.LogMapper;
import com.bwie.mapper.UserMapper;
import com.bwie.pojo.Log;
import com.bwie.pojo.User;
import com.bwie.utils.MobileMessageUtil;
import com.bwie.utils.R;
import com.bwie.vo.PageInfoVo;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bwie.pojo.Type;
import com.bwie.mapper.TypeMapper;
import com.bwie.service.TypeService;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;

@Service
@Transactional
public class TypeServiceImpl extends ServiceImpl<TypeMapper, Type> implements TypeService{
    @Autowired
    private TypeMapper typeMapper;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private LogMapper logMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public R getTypeList(PageInfoVo pageInfoVo) {
        Page<Type> typePage = new Page<>(pageInfoVo.getPageNum(),pageInfoVo.getPageSize());
        Page<Type> types = typeMapper.selectList(typePage, pageInfoVo.getTypeId());
        return R.OK(types);
    }

    @Override
    public R addType(Type type) {
        type.setTypeStatus("0");
        typeMapper.insert(type);
        Log log1 = new Log();
        log1.setLogName("房型添加");
        log1.setLogBody(JSON.toJSONString(type));
        log1.setLogTime(new Date());
        log1.setLogIp(request.getRemoteAddr());
        logMapper.insert(log1);
        return R.OK();
    }

    @Override
    public R updateType(Type type) {
        Type type1 = typeMapper.selectById(type.getTypeId());
        if(ObjectUtils.isEmpty(type1)){
            return R.ERROR(500,"房型不存在");
        }
        if(type.getTypeStatus().equals(2) && StringUtils.isEmpty(type.getTypeContent())){
            return R.ERROR(500,"请填写驳回原因");
        }
        typeMapper.updateById(type);
        //发送短信
        String token = request.getHeader("token");
        Claims body = Jwts.parser().setSigningKey("123456").parseClaimsJws(token).getBody();
        Integer id = body.get("id", Integer.class);
        User user = userMapper.selectById(id);
        String userPhone = user.getUserPhone();
        MobileMessageUtil.sendMobileMessage(userPhone,"房型审核成功");
        Log log1 = new Log();
        log1.setLogName("房型修改");
        log1.setLogBody(JSON.toJSONString(type));
        log1.setLogTime(new Date());
        log1.setLogIp(request.getRemoteAddr());
        logMapper.insert(log1);
        return R.OK();
    }


}
